package sensor

import (
	"fmt"
	"log"
	"time"
)

// ElecParser 电导率传感器解析器
type ElecParser struct {
	expectedLength int
}

func NewElecParser(dataLength int) *ElecParser {
	return &ElecParser{
		expectedLength: dataLength, // 应该是6字节
	}
}

func (p *ElecParser) Validate(data []byte) bool {
	if len(data) != p.expectedLength {
		log.Printf("电导率传感器数据长度错误: 期望%d字节, 实际%d字节", p.expectedLength, len(data))
		return false
	}
	
	// 检查模块地址是否为0xAA
	if data[0] != 0xAA {
		log.Printf("电导率传感器模块地址错误: 期望0xAA, 实际0x%X", data[0])
		return false
	}
	
	// 计算校验和: B1+B2+B3+B4+B5 取低8位
	calculatedChecksum := byte(0)
	for i := 0; i < 5; i++ { // B1到B5
		calculatedChecksum += data[i]
	}
	
	actualChecksum := data[5] // B6是校验和
	
	if calculatedChecksum != actualChecksum {
		log.Printf("电导率传感器校验和错误: 计算值0x%X, 实际值0x%X", calculatedChecksum, actualChecksum)
		log.Printf("详细计算: 字节[0-4]和=0x%X", calculatedChecksum)
		return false
	}
	
	//log.Printf("电导率传感器校验和正确: 0x%X", calculatedChecksum)
	return true
}

func (p *ElecParser) Parse(data []byte) (*SensorData, error) {
	if !p.Validate(data) {
		return nil, fmt.Errorf("invalid elec data format")
	}

	// 解析电导率值: B2 * 256 + B3
	conductivityHigh := uint16(data[1])
	conductivityLow := uint16(data[2])
	conductivityValue := conductivityHigh*256 + conductivityLow
	
	// 解析温度值: B4 * 256 + B5
	temperatureHigh := uint16(data[3])
	temperatureLow := uint16(data[4])
	temperatureRawValue := temperatureHigh*256 + temperatureLow
	temperatureValue := float64(temperatureRawValue) / 100.0 // 除以100得到实际温度
	
	//log.Printf("电导率传感器解析结果: 电导率=%d uS/cm, 温度=%.1f°C", conductivityValue, temperatureValue)
	
	return &SensorData{
		SensorType: "elec",
		Values: map[string]interface{}{
			"conductivity":       conductivityValue,  // 电导率值
			"temperature":        temperatureValue,    // 温度值
			"conductivity_high":  data[1],            // 电导率高字节
			"conductivity_low":   data[2],            // 电导率低字节
			"temperature_high":  data[3],            // 温度高字节
			"temperature_low":   data[4],            // 温度低字节
			"temperature_raw":    temperatureRawValue, // 温度原始值
		},
		RawData:   fmt.Sprintf("%X", data),
		Timestamp: time.Now(),
	}, nil
}